<?php
/**
 * @file
 * Adapter for MySQL-Result
 *
 * @category   rpd
 * @package    Db
 * @subpackage Db_Statement_MySQL
 * @copyright  Copyright (c) 2010 Rpd-Team (http://code.google.com/p/rpd)
 * @license    BSD License
 * @link       http://code.google.com/p/rpd/wiki/Db_Statement
 * @since      0.0.1
 * @version    0.0.1
 */

 /**
 * Interact on a executed statement
 *
 * This is an adapter to iterate over MySQL-Results.
 *
 * See also:
 *  @see Db_Adapter_MySQL
 *
 * @author pretzlaw
 */

class Db_Statement_MySQL implements Db_Statement_Interface
{
	/**
	 *
	 * @var resource
	 */
	private $_result = NULL;

	/** List of columns / fields
	 * @var array List of fields
	 */
	private $_fields = array();

	/**
	 * Amount of columns / fields
	 *
	 * @var integer Number of fields
	 */
	private $_num_fields = 0;

	/**
	 * Current row for iterator
	 *
	 * @var iterator
	 */
	private $_pos = 0;

	/**
	 * Get a special row
	 *
	 * @param $num integer Rownumber
	 * @return ArrayObject
	 */
	function row($num)
	{
		if ($num > 0)
		{
			mysql_result($this->_result, $num-1);
		}
		return new ArrayObject(mysql_fetch_assoc($this->_result));
	}

	/**
	 * Get list of fields
	 *
	 * @return array
	 */
	public function fields()
	{
		if (empty($this->_fields))
		{
			for ($i = 0; $i <mysql_num_fields($this->_result); $i++)
			{
				$field = mysql_field_name($this->_result, $i);
				$this->_fields[$field] = $field;
			}
		}
		return $this->_fields;
	}

	function __get($offset)
	{
		$this->row(0)->$offset;
	}

	public function current ()
	{
		return $this->row($this->_pos);
	}

	public function next ()
	{
		$this->_pos++;
		if ($this->valid())
		{
			return $this->current();
		}
		else
		{
			return false;
		}
	}

	public function key ()
	{
		return $this->_pos;
	}

	public function valid ()
	{
		return ($this->_pos < mysql_num_rows($this->_result));
	}

	public function rewind ()
	{
		$this->_pos = 0;
	}

	function __construct($result)
	{
		$this->_result = $result;
	}
}